﻿/*****************************************************************
// Copyright (C) 2011-2099 ZdSoft Corporation
// All rights reserved.
// 
// Author:       wunaigong
// Create Date:  2011-07-20 22:15:47
// Usage: 程序操作类
//
// RevisionHistory
// Date				Author				Description
*****************************************************************/

using System;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Portal
{
    public class AppGlobals
    {
        /// <summary>
        /// Bytes 转 string
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string BytesToString(byte[] obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            var result = string.Empty;
            foreach (byte o in obj)
            {
                result = result + o.ToString();
            }
            return result;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="o"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static LicenceInfo Deserialize(LicenceInfo o, string fileName)
        {
            try
            {
                var ser = new XmlSerializer(o.GetType());
                o.GetType();
                var fs = new FileStream(GetAppPath() + @"\" + fileName, FileMode.Open);
                var reader = new XmlTextReader(fs);
                return (LicenceInfo) ser.Deserialize(reader);
            }
            catch (Exception)
            {
                return new LicenceInfo();
            }
        }

        //public static void ErrorInfo(string msg)
        //{
        //    MessageBox.Show(msg, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        //}

        /// <summary>
        /// 还回 程序目录 路径
        /// </summary>
        /// <returns>路径</returns>
        public static string GetAppPath()
        {
            return System.Web.HttpContext.Current.Server.MapPath("~/bin");
            //return Application.StartupPath;
        }


        /// <summary>
        /// 还回唯一值
        /// </summary>
        /// <returns></returns>
        public static string GetOnlyOneValue()
        {
            return (DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Ticks.ToString());
        }

        /// <summary>
        /// 从资源中还回文本
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>文本</returns>
        public static string GetTextFromResource(string fileName)
        {
            string str;
            try
            {
                var assembly = Assembly.GetExecutingAssembly();
                fileName = assembly.GetName().Name + "." + fileName;
                str = new StreamReader(assembly.GetManifestResourceStream(fileName)).ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return str;
        }

        /// <summary>
        /// 从资源中还回文本
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="key">指定资源的值键</param>
        /// <returns>文本</returns>
        public static string GetTextFromResource(string fileName, string key)
        {
            string str;
            try
            {
                var asm = Assembly.GetExecutingAssembly();
                str = new ResourceManager(fileName, asm).GetString(key);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return str;
        }

        //public static void Infomation(string msg)
        //{
        //    MessageBox.Show(msg, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        //}

        public static long PrepareIP(string sip)
        {
            string[] tip = sip.Split(new char[] { ".".ToCharArray()[0] });
            return (long) ((((((Convert.ToInt32(tip[0]) * 256) * 256) * 256) + ((Convert.ToInt32(tip[1]) * 256) * 256)) + (Convert.ToInt32(tip[2]) * 256)) + Convert.ToInt32(tip[3]));
        }

        /// <summary>
        /// 生成随机密码
        /// </summary>
        /// <returns>随机密码</returns>
        public static string PreparePassword()
        {
            const int max = 99999999;
            const int min = 10000000;
            var random = new Random();
            return random.Next(min, max).ToString();
        }

        //public static DialogResult Question(string msg)
        //{
        //    return MessageBox.Show(msg, "确认提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        //}

        /// <summary>
        /// 从指定的文件中读取
        /// </summary>
        /// <param name="filename">文件名称</param>
        /// <returns>文件内容</returns>
        public static string ReadTextFromFile(string filename)
        {
            if (File.Exists(filename))
            {
                StreamReader sr = File.OpenText(filename);
                string t = sr.ReadToEnd();
                sr.Close();
                return t;
            }
            return string.Empty;
        }

        /// <summary>
        /// 读取Xml文档
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static XmlDocument ReadXml(string fileName)
        {
            var reader = new XmlTextReader(fileName);
            reader.WhitespaceHandling = WhitespaceHandling.None;
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(reader);
            reader.Close();
            return xmlDoc;
        }

        public static bool Serialize(LicenceInfo o, string fileName)
        {
            try
            {
                var ser = new XmlSerializer(o.GetType());
                var fs = new FileStream(GetAppPath() + @"\" + fileName, FileMode.Create);
                var writer = new XmlTextWriter(fs, new UTF8Encoding());
                ser.Serialize((XmlWriter) writer, o.GetType());
                writer.Close();
            }
            catch (Exception)
            {
                return false;
            }
            return false;
        }

        //public static void Warning(string msg)
        //{
        //    MessageBox.Show(msg, "警告提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        //}

        /// <summary>
        /// 反写到文件中
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="content">内容</param>
        /// <returns></returns>
        public static bool WriteTextToFile(string filename, string content)
        {
            //检测文件是否存在,存在则删除
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            //创建文件
            File.Create(filename).Close();
            var sw = new StreamWriter(filename, true, Encoding.Unicode);
            sw.Write(content);
            sw.Close();
            return true;
        }
    }
}